<style lang="less" scoped>
.icon-search {
  margin-left: 0.2rem;
  padding-left:0.2rem;
  border-left:1px solid #ccc
}
.transfer {
  p {
    margin:0 0 0.2rem 0;
    border: 1px solid rgba(0,0,0,0.1);
    padding: .2rem;
    border-radius: 5px;
    &:last-of-type {
      margin:0;
    }
    input {
      width:5rem;
    }
  }
}
</style>

<template>
  <div class="contain transferAll">
    <div class="transMask" v-if="showMask"></div>
    <app-head :show="showstate" :title="pagetitle"></app-head>
    <div class="ft14">
      <tab bar-active-color="#23a5a5" defaultColor="#333333" active-color="#23a5a5" :line-width='2' v-model="tabNo">
        <tab-item @on-item-click="tabNo = 0">整车中转</tab-item>
        <tab-item @on-item-click="tabNo = 1">区域中转</tab-item>
      </tab>
    </div>

    <div class="car-bbinfo-card">
      <div class="bbno lineb">排车单号：{{data.ATVNo}}</div>
    </div>

    <div class="car-bbinfo-card"  style="position:relative" v-if='tabNo === 1'>
      <div class="bbmain lineb">
        <popup-picker style="z-index:1; background:transparent" :title="AreaPickerTitle" :data="AreaList" v-model="selectedArea" @on-change="getText" :placeholder="'请选择'" :show-name="true"></popup-picker>
        <div style="position:absolute; top:0.2rem; right:0.45rem; font-size:16px; z-index:0; color:#888">{{selectedTextArea}}</div>
      </div>
    </div>

    <div class="car-bbinfo-card">
      <div class="bbmain mb30">
        <p class="displayflex"><i>配送路线</i><label class="flex1">{{data.routeName}}</label></p>
        <p class="displayflex"><i>承运商</i><label class="flex1">{{data.deliverName}}</label></p>
        <p class="displayflex"><i>派单司机</i><label class="flex1">{{data.driver1Name}}</label></p>
        <p class="displayflex"><i>订单数</i><label class="flex1">{{data.length}}件</label></p>
        <p class="displayflex"><i>总件数</i><label class="flex1">{{data.totalPkgs}}件</label></p>
      </div>
    </div>

    <div class="car-bbinfo-card">
      <div class="bbmain mb30">
        <p class="displayflex"><i>取货地址数</i><label class="flex1">{{data.depAddressList.length}}</label></p>
        <p class="displayflex"><i>送货地址数</i><label class="flex1">{{data.arrivalAddressCount}}</label></p>
        <p class="displayflex"><i>客户数</i><label class="flex1">{{data.cutomerCount}}</label></p>
      </div>
    </div>

    <template v-if="tabNo === 0">
      <div data class="car-bbinfo-card">
        <div data class="bbmain lineb ">
          <div data class="vux-cell-box" v-on:click="showDepAddress=true">
            <div class="weui-cell vux-tap-active weui-cell_access">
              <div class="weui-cell__hd">
                <label class="weui-label" style="display: block; width: auto;">共计{{data.depAddressList.length}}个取货地址</label>
              </div>
              <div class="vux-cell-primary vux-popup-picker-select-box">
                <div class="vux-popup-picker-select" style="text-align: right;">
                  <span class="vux-popup-picker-placeholder vux-cell-placeholder">查看</span>
                </div>
              </div>
              <div class="weui-cell__ft"></div>
            </div>
          </div>
        </div>
      </div>
      <div data class="car-bbinfo-card mb30">
        <div data class="bbmain lineb ">
          <div data class="vux-cell-box" v-on:click="showArrAddress=true">
            <div class="weui-cell vux-tap-active weui-cell_access">
              <div class="weui-cell__hd">
                <label class="weui-label" style="display: block; width: auto;">共计{{data.arrAddressList.length}}个送货地址</label>
              </div>
              <div class="vux-cell-primary vux-popup-picker-select-box">
                <div class="vux-popup-picker-select" style="text-align: right;">
                  <span class="vux-popup-picker-placeholder vux-cell-placeholder">查看</span>
                </div>
              </div>
              <div class="weui-cell__ft"></div>
            </div>
          </div>
        </div>
      </div>
    </template>

    <div class="car-bbinfo-card mb30 transfer">
      <div class="bbno lineb">交接信息</div>
      <div class="bbmain">
        <p><input type="text" placeholder="输入或选择物流公司" v-model="carrierText" v-on:blur="setCarrier" />
          <label>
            <i class="iconfont icon-search" v-on:click="showCarrier = true"></i>
          </label>
        </p>
        <p><input type="text" placeholder="输入物流单号" />
          <label></label>
        </p>
        <p><input type="text" placeholder="输入车牌号"/>
          <label></label>
        </p>
      </div>
    </div>

    <div class="car-bbinfo-card">
      <div class="bbmain mb30">
        <x-textarea v-model="Memo" :placeholder="'备注'" :max="200" autosize style="color:#888; font-size:16px;"></x-textarea>
      </div>
    </div>

    <uploader :title="'上传中转凭据'" :img-list="imgList" :max="max"></uploader>

    <div class="displayflex form-btn" v-if="tabNo === 0">
      <div class="flex1" v-on:click="transAll()">确认整车中转</div>
    </div>

    <div class="displayflex form-btn" v-if="tabNo === 1">
      <div class="flex1" v-on:click="transRegion()">确认区域中转</div>
    </div>

    <popup-picker :show.sync="showCarrier" show-name :show-cell="false" title="TEST" :data="carriers" v-model="selectedCarrier" ref="carrierPicker"></popup-picker>

    <actionsheet v-model="showDepAddress" :menus="data.depAddressList" show-cancel :cancel-text="'关闭'">
      <p slot="header" v-html="tipD"></p>
    </actionsheet>
    <actionsheet v-model="showArrAddress" :menus="data.arrAddressList" show-cancel :cancel-text="'关闭'">
      <p slot="header" v-html="tipA"></p>
    </actionsheet>

  </div>
</template>

<script>
import appHead from '@/components/core/header/app_headbar.vue';
import tools from '../../tools/tool.js';
import uploader from '@/components/share/imageUploader/imageUploader.vue';
import { mapState } from "vuex";

export default {
  components:{
    uploader,
    appHead,
  },
  data(){
    return {
      data:{
        ATVNo: '',
        Guid:'',
        routeName: '',
        deliverName:'',
        driver1Name:'',
        totalPkgs:0,
        arrivalAddressCount:0,
        cutomerCount:0,
        depAddressList:[],
        arrAddressList:[],
      },
      datas:{},
      Memo:'',

      tabNo: 0,
      showDepAddress:false,
      showArrAddress:false,
      visibility: false,
      leaveDate:'',
      pickerStartDate:'',
      pickerEndDate:'',
      filter: this.$options.filters,
      AreaList:[],
      selectedArea:[],
      selectedTextArea:'',
      carriers:[],
      imgList:[],
      max:9,
      showCarrier:false,
      carrierText:'',
      selectedCarrier:[],
      showMask:false,
      manualCarriers: [],
    }
  },
  watch: {
    selectedArea:{
      handler(n,o){
        if(n.toString() !== o.toString()){
          this.getData();
        }
      },
      deep:true
    },
    selectedCarrier:{
      handler(n,o){
        this.carrierText = this.$refs.carrierPicker.getNameValues();
      },
      deep:true
    },
    tabNo(n,o){
      if(n === 0){
        this.AreaList = [];
        this.selectedArea = [];
        this.selectedTextArea = '';
        this.getData();
      } else {
        this.selectedArea.splice(0,1,this.AreaList[0][0].value);
        this.getData();
      }
    }
  },
  computed: {
    AreaPickerTitle(){
      return `共计${this.AreaList[0].length}个取货地`;
    },
    tipD(){
      return `起始地<br><span class="actitle">共计${this.data.depAddressList.length}个地址</span>`;
    },
    tipA(){
      return `目的地<br><span class="actitle">共计${this.data.arrAddressList.length}个地址</span>`;
    },
    ...mapState({
      pagetitle: state => state.cfg.appBarTitle,
      showstate: state => state.cfg.showAppBar,
    }),
    userinfo(){
      return localStorage.userinfo?JSON.parse(localStorage.userinfo):null
    }
  },
  created(){
    this.getCarriers();
    this.getData();
  },
  mounted(){
    
  },
  methods:{
    transAll(){
      let _this = this;
      if(this.validate()){
        this.$vux.confirm.show({
          content: '确认进行整车中转？',
          onCancel () {
            return false;
          },
          onConfirm () {
            _this.goTrans();
          }
        })
      }
    },
    transRegion(){
      let _this = this;
      if(this.validate()){
        this.$vux.confirm.show({
          content: '确认进行区域中转？',
          onCancel () {
            return false;
          },
          onConfirm () {
            _this.goTrans();
          }
        })
      }
    },
    goTrans(){
      let atvehicleDetail = [];
      this.datas.forEach((x) => {
        let item = {
          Guid: x.Guid,
          RowNo: x.RowNo,
        }
        atvehicleDetail.push(item);
      })

      let imgList = this.$sortImage(this.imgList);
      
      let query ={
        Guid: this.data.Guid,
        Memo: this.Memo,
        PRContactsTel: this.userinfo.MobileTel1,
        RPName: this.carrierText,
        Rpguid: this.selectedCarrier[0],
        imgList: imgList,
        AtvehicleDetail: atvehicleDetail,
      }
      this.showMask = true;
      this.Ajax.post("TransferOrder", query).then(resp => {
        if (resp.IsSuccess) {
          this.Toast({
            message: '操作成功',
            duration: 1000,
          });
          setTimeout(() => { this.$router.go(-1) }, 1000);
        } else {
          this.Toast({
            message: resp.ErrorMessage,
            duration: 1000,
          });
          setTimeout(() => { this.$router.go(-1) }, 1000);
        }
      }).catch((e) => {
        this.showMask = false;
        this.Toast({
          message: "出现错误，请刷新重试"
        });
      });
    },

    validate(){
      if(this.selectedCarrier.length === 0){
        this.Toast({message: '请设置物流公司'});
        return false;
      }
      return true;
    },
    
    getCarriers(){
      let query = {
        CorpGuid : this.userinfo.CorpGuid,
      };
      this.Ajax.post("SearchCorpCarrier", query).then(resp => {
        if(resp.IsSuccess){
          let carriers = [];
          resp.Datas.forEach((x) => {
            if(x.Guid !== this.userinfo.BelongGuid){
              let item = {
                name: x.ChineseName,
                value: x.Guid,
              }
              carriers.push(item);
            }
          })
          if(carriers.length > 0){
            this.carriers.push(carriers);
          }
        } else {
          this.Toast({
            message: resp.ErrorMessage
          });
        }
      });
    },

    getData(){
      let query = {
        Guid: this.$route.query.Guid,
        LogState: 52,
        PageIndex:1,
        PageSize:99999,
      }
      if(this.selectedArea.length > 0){
        let arg = JSON.parse(JSON.stringify(this.selectedArea))[0];
        if(typeof(arg) === 'string'){
          arg = arg.split(',');
        }
        query.DepartureProvince = arg[0];
        query.DepartureCity = arg[1];
      }
      this.Ajax.post("SearchPickUpOrders", query).then(resp => {
        if (resp.IsSuccess) {
          this.datas = resp.Datas;

          let depAddr = [],
              arrAddr = [],
              totalPkgs = 0,
              customer = [];

          
          resp.Datas.forEach((x) => {
            let depCode = `${x.DepartureProvince}${x.DepartureCity}`,
                depText = `${this.filter.province(x.DepartureProvince)}${this.filter.city(x.DepartureCity)}`,
                depCodeArr = [x.DepartureProvince, x.DepartureCity],
                arrCode = `${x.ArrivalProvince}${x.ArrivalCity}`,
                arrText = `${this.filter.province(x.ArrivalProvince)}${this.filter.city(x.ArrivalCity)}`,
                arrCodeArr = [x.ArrivalProvince, x.ArrivalCity],
                depItem = {
                  name: depText,
                  label: depText,
                  value: depCodeArr,
                  code: depCode,
                },
                arrItem = {
                  name: arrText,
                  label: arrText,
                  value: arrCodeArr,
                  code: arrCode,
                };
            totalPkgs += x.Pkgs;
            customer.push(x.PickContacts);
            depAddr.push(depItem);
            arrAddr.push(arrItem);
          })
          
          depAddr = this.mapReduce(depAddr, 'code');
          arrAddr = this.mapReduce(arrAddr, 'code');
          customer = [...new Set(customer)];
          if(this.AreaList.length === 0){
            this.AreaList.push(depAddr);
          }
          

          this.data.ATVNo = resp.Datas[0].ATVNo,
          this.data.Guid = resp.Datas[0].Guid,
          this.data.routeName = resp.Datas[0].RouteName,
          this.data.deliverName = resp.Datas[0].DeliverName,
          this.data.driver1Name = resp.Datas[0].Driver1Name,
          this.data.totalPkgs = totalPkgs,
          this.data.arrivalAddressCount = arrAddr.length,
          this.data.cutomerCount = customer.length;
          this.data.depAddressList = depAddr;
          this.data.arrAddressList = arrAddr;

        } else {
          this.Toast({
            message: "列表为空，请稍后刷新"
          });
        }
      });
    },

    setCarrier(e){
      let text = e.target.value;
      let item = {
        value: (this.carriers.length + 1).toString(),
        name: text
      },
      selItem = [(this.carriers.length + 1).toString()];
      this.manualCarriers.push(item);
      this.carriers.splice(0,1,this.manualCarriers);
      this.selectedCarrier = selItem;
    },

    getText(e){
      let arg = e[0];
      if(typeof(arg) === 'string'){
        arg = e[0].split(',');
      }
      this.selectedTextArea = `${this.filter.province(arg[0])}${this.filter.city(arg[1])}`;
    },

    mapReduce(arr, keyName){
      let obj = {};
      arr = arr.reduce((item, next) => {
        obj[next[keyName]] ? '' : obj[next[keyName]] = true && item.push(next);
        return item;
      }, []);
      return arr;
    },
  },
}
</script>
